import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router';

export default class UserEntry extends Component {
  constructor(props) {
    super(props);
    this.state = {
      menuExpand: false,
    };
    this.toggleMenu = this.toggleMenu.bind(this);
    this.signOut = this.signOut.bind(this);
  }

  toggleMenu() {
    this.setState(prevState => ({ menuExpand: !prevState.menuExpand }));
  }

  signOut() {
    const { rootAction } = this.props;
    rootAction.signOut().then(() => {
      window.location.href = '/';
    });
  }

  render() {
    return (
      <div id="user-account">
        {this.props.userProfile && (
          <button onClick={this.toggleMenu}>{this.props.userProfile.nickname}</button>
        )}
        {this.props.userProfile && this.state.menuExpand && (
          <ul className="profile-list">
            <li onClick={this.signOut} className="profile-item">注销</li>
          </ul>
        )}
        {!this.props.userProfile && (
          <Link to="/login">登录</Link>
        )}
      </div>
    );
  }
}

UserEntry.propTypes = {
  userProfile: PropTypes.object,
  rootAction: PropTypes.object
};
